import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import { Card } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Toaster } from '@/components/ui/toaster'
import { useToast } from '@/hooks/use-toast'

interface ImageSliceData {
  id: string
  x: number
  y: number
  width: number
  height: number
  name: string
}

export default function ImageGallery() {
  const [selectedImages, setSelectedImages] = useState<string[]>([])
  const [sliceImages, setSliceImages] = useState<{ [key: string]: string }>({})
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const { toast } = useToast()

  // 默认配置 - 5行5列，有间距
  const imageUrl = '/api/g/f/p/14097'

  // 使用 useMemo 包装 defaultSliceData 以避免每次渲染时重新创建
  const defaultSliceData: ImageSliceData[] = useMemo(() => {
    const data: ImageSliceData[] = []

    // 生成默认测试数据
    const cellWidth = 28
    const cellHeight = 28
    const offsetX = 5
    const offsetY = 2
    const rowSpacing = 10
    const colSpacing = 10

    let id = 1
    for (let row = 0; row < 5; row++) {
      for (let col = 0; col < 5; col++) {
        const x = offsetX + col * (cellWidth + colSpacing)
        const y = offsetY + row * (cellHeight + rowSpacing)

        data.push({
          id: id.toString(),
          x,
          y,
          width: cellWidth,
          height: cellHeight,
          name: `图片_${id}`
        })
        id++
      }
    }

    return data
  }, []) // 空依赖数组，因为这些值是常量

  // 切割图片
  const extractImages = useCallback(async () => {
    if (!imageUrl || defaultSliceData.length === 0) return

    const canvas = canvasRef.current
    if (!canvas) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    const img = new Image()
    img.crossOrigin = 'anonymous'

    img.onload = () => {
      const extractedImages: { [key: string]: string } = {}

      defaultSliceData.forEach((slice) => {
        // 设置 canvas 尺寸为单个切片的尺寸
        canvas.width = slice.width
        canvas.height = slice.height

        // 清空 canvas
        ctx.clearRect(0, 0, slice.width, slice.height)

        // 从大图中切出对应位置的小图
        ctx.drawImage(
          img,
          slice.x,
          slice.y,
          slice.width,
          slice.height,
          0,
          0,
          slice.width,
          slice.height
        )

        // 将切出的图片转换为 base64
        extractedImages[slice.id] = canvas.toDataURL('image/png')
      })

      setSliceImages(extractedImages)
    }

    img.onerror = () => {
      console.error('Failed to load image')
      toast({
        title: '图片加载失败',
        description: '请检查图片URL是否正确'
      })
    }

    img.src = imageUrl
  }, [imageUrl, defaultSliceData, toast])

  useEffect(() => {
    extractImages()
  }, [extractImages])

  // 切换图片选择状态
  const toggleImageSelection = (imageId: string) => {
    setSelectedImages((prev) => {
      if (prev.includes(imageId)) {
        return prev.filter((id) => id !== imageId)
      } else {
        return [...prev, imageId]
      }
    })
  }

  // 全选
  const selectAll = () => {
    setSelectedImages(defaultSliceData.map((slice) => slice.id))
    toast({
      title: '已全选',
      description: '选中了所有25张图片'
    })
  }

  // 取消全选
  const clearSelection = () => {
    setSelectedImages([])
    toast({
      title: '已清空选择',
      description: '取消了所有图片的选择'
    })
  }

  // 导出选中的图片ID
  const exportSelection = () => {
    const selectedData = defaultSliceData.filter((slice) =>
      selectedImages.includes(slice.id)
    )

    const dataStr = JSON.stringify(
      {
        selectedIds: selectedImages,
        selectedData: selectedData,
        imageUrl: imageUrl
      },
      null,
      2
    )

    navigator.clipboard.writeText(dataStr)
    toast({
      title: '选择数据已复制',
      description: `已复制${selectedImages.length}张图片的数据到剪贴板`
    })
  }

  return (
    <div className="container mx-auto max-w-6xl p-6">
      <div className="space-y-6">
        {/* 标题 */}
        <div className="text-center">
          <h1 className="mb-2 text-3xl font-bold">图片画廊选择器</h1>
          <p className="text-gray-600">浏览并选择你需要的图片（1-25）</p>
        </div>

        {/* 操作栏 */}
        <Card className="p-4">
          <div className="flex flex-wrap items-center justify-between gap-4">
            <div className="flex items-center gap-2">
              <Badge variant="secondary">
                已选择: {selectedImages.length} / {defaultSliceData.length}
              </Badge>
              <Badge variant="outline">图片源: {imageUrl}</Badge>
            </div>

            <div className="flex gap-2">
              <Button
                onClick={selectAll}
                variant="outline"
                size="sm"
                disabled={selectedImages.length === defaultSliceData.length}
              >
                全选
              </Button>
              <Button
                onClick={clearSelection}
                variant="outline"
                size="sm"
                disabled={selectedImages.length === 0}
              >
                清空
              </Button>
              <Button
                onClick={exportSelection}
                variant="default"
                size="sm"
                disabled={selectedImages.length === 0}
              >
                导出选择 ({selectedImages.length})
              </Button>
            </div>
          </div>
        </Card>

        {/* 图片网格 */}
        <Card className="p-6">
          <h2 className="mb-4 text-xl font-semibold">📷 图片列表</h2>

          <ScrollArea className="h-[600px]">
            <div className="grid grid-cols-5 gap-4 p-2">
              {defaultSliceData.map((slice) => (
                <div
                  key={slice.id}
                  className={`relative flex cursor-pointer flex-col items-center rounded-lg border-2 p-3 transition-all ${
                    selectedImages.includes(slice.id)
                      ? 'border-blue-500 bg-blue-50 shadow-md'
                      : 'border-gray-200 bg-white hover:border-gray-300 hover:shadow-sm'
                  }`}
                  onClick={() => toggleImageSelection(slice.id)}
                >
                  {/* 选中状态指示器 */}
                  <div
                    className={`absolute -right-2 -top-2 flex size-6 items-center justify-center rounded-full border-2 text-xs font-bold transition-all ${
                      selectedImages.includes(slice.id)
                        ? 'border-blue-500 bg-blue-500 text-white'
                        : 'border-gray-300 bg-white text-gray-400'
                    }`}
                  >
                    {selectedImages.includes(slice.id) ? '✓' : slice.id}
                  </div>

                  {/* 图片容器 */}
                  <div className="mb-2 flex size-16 items-center justify-center rounded border bg-gray-50">
                    {sliceImages[slice.id] ? (
                      <img
                        src={sliceImages[slice.id]}
                        alt={slice.name}
                        className="size-full object-contain"
                      />
                    ) : (
                      <div className="text-xs text-gray-400">加载中...</div>
                    )}
                  </div>

                  {/* 图片信息 */}
                  <div className="text-center">
                    <div className="text-sm font-medium">{slice.name}</div>
                    <div className="text-xs text-gray-500">ID: {slice.id}</div>
                    <div className="text-xs text-gray-400">
                      {slice.width}×{slice.height}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </ScrollArea>

          {/* 加载状态 */}
          {Object.keys(sliceImages).length === 0 && (
            <div className="py-8 text-center text-gray-500">
              <div className="inline-flex items-center gap-2">
                <div className="size-4 animate-spin rounded-full border-2 border-blue-500 border-t-transparent"></div>
                正在加载图片...
              </div>
            </div>
          )}
        </Card>

        {/* 选中的图片预览 */}
        {selectedImages.length > 0 && (
          <Card className="p-6">
            <h2 className="mb-4 text-xl font-semibold">✅ 已选择的图片</h2>
            <div className="flex flex-wrap gap-2">
              {selectedImages.map((imageId) => {
                const slice = defaultSliceData.find((s) => s.id === imageId)
                if (!slice) return null

                return (
                  <div key={imageId} className="group relative">
                    <div className="size-12 overflow-hidden rounded border bg-gray-50">
                      {sliceImages[imageId] && (
                        <img
                          src={sliceImages[imageId]}
                          alt={slice.name}
                          className="size-full object-contain"
                        />
                      )}
                    </div>
                    <div className="absolute -right-1 -top-1 flex size-5 items-center justify-center rounded-full bg-blue-500 text-xs text-white">
                      {imageId}
                    </div>
                    {/* 删除按钮 */}
                    <button
                      onClick={(e) => {
                        e.stopPropagation()
                        toggleImageSelection(imageId)
                      }}
                      className="absolute -left-1 -top-1 hidden size-5 items-center justify-center rounded-full bg-red-500 text-xs text-white opacity-0 transition-opacity group-hover:flex group-hover:opacity-100"
                    >
                      ×
                    </button>
                  </div>
                )
              })}
            </div>
          </Card>
        )}

        {/* 使用说明 */}
        <Card className="bg-gray-50 p-6">
          <h2 className="mb-4 text-xl font-semibold">📖 使用说明</h2>
          <div className="grid grid-cols-1 gap-4 text-sm md:grid-cols-2">
            <div>
              <h3 className="mb-2 font-medium">基本操作</h3>
              <ul className="space-y-1 text-gray-600">
                <li>• 点击图片可以选择/取消选择</li>
                <li>• 使用&quot;全选&quot;按钮选择所有图片</li>
                <li>• 使用&quot;清空&quot;按钮取消所有选择</li>
                <li>• 点击&quot;导出选择&quot;复制数据到剪贴板</li>
              </ul>
            </div>
            <div>
              <h3 className="mb-2 font-medium">数据格式</h3>
              <ul className="space-y-1 text-gray-600">
                <li>• 导出的数据包含选中的图片ID</li>
                <li>• 包含完整的切片配置信息</li>
                <li>• 可直接用于其他组件或API</li>
                <li>• JSON格式，易于解析和使用</li>
              </ul>
            </div>
          </div>
        </Card>
      </div>

      {/* 隐藏的 canvas 用于图片处理 */}
      <canvas ref={canvasRef} className="hidden" />
      <Toaster />
    </div>
  )
}
